package com.rjt.qrcode.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rjt.common.model.Address;
import com.rjt.common.util.TextUtil;
import com.rjt.qrcode.dto.QrCodeVisitDto;
import com.rjt.qrcode.model.QrCodeVisitModel;
import com.rjt.qrcode.repository.QrCodeVisitRepository;
import com.rjt.qrcode.service.QrCodeVisitService;
import com.rjt.qrcode.vo.QrCodeVisitVo;
@Service
public class QrCodeVisitServiceImpl implements QrCodeVisitService {
	
	
	@Autowired
	private QrCodeVisitRepository qrcodeVisitRepository;
	
	
	@Override
	public void save(String rId, HttpServletRequest request) {
		// TODO Auto-generated method stub
		try {
			QrCodeVisitModel qrcodeVisitModel = new QrCodeVisitModel();
			qrcodeVisitModel.setqId(rId);
			qrcodeVisitModel.setCreateDate(new Date());
			String remortIP = TextUtil.getRemortIP(request);
			System.out.println("类QrCodeVisitServiceImpl获取的远端的ip"+remortIP);
			if(Objects.isNull(remortIP)) {
				return ;
			}
			qrcodeVisitModel.setIp(remortIP);
			Address place = TextUtil.getPlace(remortIP);
			qrcodeVisitModel.setRegion(place.getProvince());
			qrcodeVisitModel.setCity(place.getCity());
			qrcodeVisitRepository.save(qrcodeVisitModel);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("保存访客信息失败了,可能是重复的ip,错误代码"+e.getMessage());
		}
		
	}
	@Override
	public List<QrCodeVisitVo> countByRIdAndArea(String rId) {
		// TODO Auto-generated method stub
		 List<QrCodeVisitVo> countByArea =new ArrayList<>();
		 List<QrCodeVisitDto> countByRIdAndArea = qrcodeVisitRepository.countByRIdAndArea(rId);
		 countByRIdAndArea.forEach(dto->{
			 QrCodeVisitVo qrCodeVisitVo = new QrCodeVisitVo();
			 qrCodeVisitVo.setName(dto.getRegion()+dto.getCity());
			 qrCodeVisitVo.setValue(dto.getValue());
			 countByArea.add(qrCodeVisitVo);
		 });
		 return countByArea;
		 
	}
	
	
	@Override
	public List<QrCodeVisitVo> countByRIdAndDate(String rId) {
		// TODO Auto-generated method stub
		 List<QrCodeVisitVo> countByDate =new ArrayList<>();
		 List<QrCodeVisitDto> countByRIdAndDate = qrcodeVisitRepository.countByRIdAndDate(rId);
		 countByRIdAndDate.forEach(dto->{
			 QrCodeVisitVo qrCodeVisitVo = new QrCodeVisitVo();
			 qrCodeVisitVo.setName(dto.getCreateDate());
			 qrCodeVisitVo.setValue(dto.getValue());
			 countByDate.add(qrCodeVisitVo);
		 });
		 return countByDate;
		 
	}
	
}
